package com.chinacoal.microservice.impl.controller;

import java.util.List;
import java.util.Map;

import javax.annotation.Resource;

import org.springframework.web.bind.annotation.RestController;

import com.baomidou.mybatisplus.plugins.Page;
import com.chinacoal.microservice.api.WorkflowClient;
import com.chinacoal.microservice.exception.MessageException;
import com.chinacoal.microservice.impl.mapper.WorkItemMapper;
import com.chinacoal.microservice.impl.service.ApprovalHistoryService;
import com.chinacoal.microservice.impl.service.TaskPushService;
import com.chinacoal.microservice.impl.service.WorkFlowService;
import com.chinacoal.microservice.impl.util.ProcessFun;
import com.chinacoal.microservice.login.LoginUser;
import com.chinacoal.microservice.model.IamUser;
import com.chinacoal.microservice.model.wofkflow.ApproveParam;
import com.chinacoal.microservice.model.wofkflow.QueryTaskListParam;
import com.chinacoal.microservice.model.wofkflow.SubmitParam;
import com.chinacoal.microservice.model.wofkflow.entity.ApprovalHistoryEntity;
import com.chinacoal.microservice.model.wofkflow.entity.InstanceEntity;
import com.chinacoal.microservice.model.wofkflow.entity.WorkItemEntity;
import com.chinacoal.microservice.model.wofkflow.resource.WorkflowVar;
import com.chinacoal.microservice.util.result.CodeMsg;
import com.chinacoal.microservice.util.result.Result;
import com.eos.workflow.api.IBPSServiceClient;

import lombok.extern.slf4j.Slf4j;


/**  
 * @Package: com.chinacoal.microservice.impl.controller.WorkFlowController
 * @ClassName: WorkFlowController
 * @ClassDesc: 工作流管理Controller
 * @Createby: sunh
 * @CreatedDate: 2019-12-02 15:30:43
 */  
@Slf4j
@RestController
public class WorkFlowController implements WorkflowClient {
	
	@Resource
	private WorkFlowService workFlowService;
	@Resource
	private ApprovalHistoryService approvalHistoryService;
	@Resource
	private LoginUser loginUser;
	@Resource
	private TaskPushService taskPushService;
	@Resource
	private WorkItemMapper workItemMapper;
	
	@Override
    public Result<InstanceEntity> processSubmit(SubmitParam submitparam){
		
		InstanceEntity instanceEntity = null;
		
		try {
			log.info("1、----------------提交流程步骤开始--------------");
			
			Integer userId = submitparam.getUserId();
			String name = submitparam.getName();
			
			if(userId == null) {
				IamUser iamUser = loginUser.getLoginUser();
				if(iamUser == null) throw new MessageException("用户未登录");
				userId = iamUser.getUserId();
				name = iamUser.getName();
			}
			
			
			// 获取工作流服务
			IBPSServiceClient client = workFlowService.getIBPSServiceClient(userId, name);
			log.info("2、------------------获取工作流服务成功：" + name + "-----------------");
			
			// 创建实例
			if(submitparam.getInstanceId() == null) {
				instanceEntity = workFlowService.createProcessInstance(client, submitparam.getProcessCode());
				submitparam.setInstanceId(instanceEntity.getInstanceId());
			}
			log.info("3、------------------创建实例成功：" + submitparam.getInstanceId() + "-----------------");
			
			// 提交流程
			instanceEntity = workFlowService.processSubmit(client, submitparam.getInstanceId(), submitparam.getBusinessParam());
			log.info("4、------------------流程提交成功-----------------");
			
			// 完成填报
			if("Y".equals(submitparam.getIsSkip())) {
				workFlowService.completeFill(client, submitparam.getInstanceId());
			}
			log.info("5、------------------完成填报成功-----------------");
			 
			return Result.success(instanceEntity);
		} catch (Exception e) {
			e.printStackTrace();
			String msg = ProcessFun.getExceptionMessage(e);
			if(instanceEntity == null) {
				return Result.error(CodeMsg.ERROR_WORKFLOW_SUBMIT.fillArgs(msg));
			}else {
				return Result.IError(CodeMsg.ERROR_WORKFLOW_INSTANCE.fillArgs(msg),instanceEntity);
			}
		}
    }
    
	@Override
    public Result<InstanceEntity> completeTask(ApproveParam approveParam){
		try {
			IamUser iamUser = loginUser.getLoginUser();
			if(iamUser == null) throw new MessageException("用户未登录");
			
			// 获取工作流服务
			IBPSServiceClient client = workFlowService.getIBPSServiceClient(iamUser.getUserId(),iamUser.getName());
			
			// 获取参数
			Long instanceId = approveParam.getInstanceId();
			Map<String, Object>  businessParam = approveParam.getBusinessParam();
			workFlowService.setBusinessDate(client, instanceId, businessParam);
			
			// 获取最新待办
			Long taskId = approveParam.getTaskId();
			List<WorkItemEntity> approvalBeforeTaskList = workItemMapper.getWorkItemByInstanceId(instanceId);
			
			// 完成待办
			InstanceEntity instanceEntity = new InstanceEntity();
			String opcode = approveParam.getOpcode();
	    	if(WorkflowVar.APPROVE_AGREED.equals(opcode)) {
	    		// 同意
	    		instanceEntity = workFlowService.approveAgreed(client, approveParam);
	    	}else if(WorkflowVar.APPROVE_REJECTED.equals(opcode)) {
	    		// 驳回
	    		instanceEntity = workFlowService.approveRejected(client, approveParam);
	    	}else if(WorkflowVar.APPROVE_RECALL.equals(opcode)) {
	    		// 撤回
	    		instanceEntity = workFlowService.approveRecall(client, approveParam);
	    	}else if(WorkflowVar.APPROVE_FALLBACK.equals(opcode)) {
	    		// 回退
	    		instanceEntity = workFlowService.approveFallback(client, approveParam);
	    	}else if(WorkflowVar.APPROVE_CONSULT.equals(opcode)) {
	    		// 征询
	    		instanceEntity = workFlowService.approveConsult(client, approveParam);
	    	}else if(WorkflowVar.APPROVE_DELEGATE.equals(opcode)) {
	    		// 委派
	    		instanceEntity = workFlowService.approveDelegate(client, approveParam);
	    	}else if(WorkflowVar.APPROVE_TRANSPOND.equals(opcode)) {
	    		// 转发
	    		instanceEntity = workFlowService.approveTranspond(client, approveParam);
	    	}else if(WorkflowVar.APPROVE_REPEAL.equals(opcode)) {
	    		// 审批撤回
	    		instanceEntity = workFlowService.approveRepeal(client, approveParam);
	    	}else if(WorkflowVar.APPROVE_TERMINATE.equals(opcode)) {
	    		// 流程终止
	    		instanceEntity = workFlowService.approveTerminate(client, approveParam);
	    	}else if(WorkflowVar.APPROVE_RESTART.equals(opcode)) {
	    		// 流程重启
	    		instanceEntity = workFlowService.approveRestart(client, approveParam);
	    	}else if(WorkflowVar.APPROVE_HANGUP.equals(opcode)) {
	    		// 流程挂起
	    		instanceEntity = workFlowService.approveHangUp(client, approveParam);
	    	}else if(WorkflowVar.APPROVE_RESTORE.equals(opcode)) {
	    		// 流程恢复
	    		instanceEntity = workFlowService.approveRestore(client, approveParam);
	    	}else {
	    		throw new Exception("无法识别的操作码【" + opcode + "】，请检查调用参数！");
	    	}
	    	
    		// 推送待办
    		List<WorkItemEntity> approvalAfterTaskList = workItemMapper.getWorkItemByInstanceId(instanceId);
	    	taskPushService.taskPush(approvalBeforeTaskList, approvalAfterTaskList, taskId, opcode);
	    	
	    	return Result.success(instanceEntity);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error(CodeMsg.ERROR_WORKFLOW_APPROVAL.fillArgs(ProcessFun.getExceptionMessage(e)));
		} 
    }
    
	@Override
	public Result<Object> deleteInstanceById(List<Long> instanceIds) {
		try {
			IamUser iamUser = loginUser.getLoginUser();
			if(iamUser == null) throw new MessageException("用户未登录");

			// 获取工作流服务
			IBPSServiceClient client = workFlowService.getIBPSServiceClient(iamUser.getUserId(),iamUser.getName());
			// 删除实例
			workFlowService.deleteInstanceById(client, instanceIds);
			
			return Result.success("删除实例成功");
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error(CodeMsg.EXECUTE_ERROR.fillArgs(ProcessFun.getExceptionMessage(e)));
		}
	}
	
	@Override
    public Result<Page<WorkItemEntity>> getTaskList(Integer page, Integer pageSize, QueryTaskListParam queryParam){
		
		try {
			IamUser iamUser = loginUser.getLoginUser();
			if(iamUser == null) throw new MessageException("用户未登录");

			queryParam.setUserId(iamUser.getUserId());
			
			// 获取待办列表
			Page<WorkItemEntity> taskList = workFlowService.getTaskList(page, pageSize, queryParam);

			return Result.success(taskList);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error(CodeMsg.ERROR_WORKFLOW_TASK.fillArgs(ProcessFun.getExceptionMessage(e)));
		} 
    }
    
	@Override
    public Result<Page<WorkItemEntity>> getAchTaskList(Integer page, Integer pageSize, QueryTaskListParam queryParam){
		
		try {
			IamUser iamUser = loginUser.getLoginUser();
			if(iamUser == null) throw new MessageException("用户未登录");

			queryParam.setUserId(iamUser.getUserId());
			
			// 获取已办列表
			Page<WorkItemEntity> taskList = workFlowService.getAchTaskList(page, pageSize, queryParam);
			
			return Result.success(taskList);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error(CodeMsg.ERROR_WORKFLOW_ACTTASK.fillArgs(ProcessFun.getExceptionMessage(e)));
		} 
    }
    
	@Override
    public Result<Page<ApprovalHistoryEntity>> getApprovalHistory(Integer page, Integer pageSize, Long instanceId){
		try {
			Page<ApprovalHistoryEntity> approvalHistoryList = approvalHistoryService.selectApprovalHistory(instanceId,page,pageSize);
			return Result.success(approvalHistoryList);
		} catch (Exception e) {
			e.printStackTrace();
			return Result.error(CodeMsg.ERROR_WORKFLOW_HISTORY.fillArgs(ProcessFun.getExceptionMessage(e)));
		} 
    }
}
